package com.moonbird.springboot.service;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.moonbird.springboot.DTO.Result;
import com.moonbird.springboot.Utils.RecognitionImage.FormRecognitionUtil;
import com.moonbird.springboot.Utils.RecognitionImage.ImageTextRecognitionUtils;
import com.moonbird.springboot.Utils.RecognitionImage.UniversalCharacterRecognitionUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;

@Service
public class PictureRecognitionTextService {

    private static final String[] SUPPORTED_FORMATS = {"jpg", "jpeg", "png", "bmp"};
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB

    public Result<String> toDocument(MultipartFile file, String type) throws InterruptedException {
        int flagNumber = validateFile(file);
        switch (flagNumber) {
            case 0:
                return Result.fail("文件名不能为空");
            case 1:
                return Result.fail("图片格式不支持");
            case 2:
                return Result.fail("文件大小超过10MB");
            case 3:
                return Result.fail("文件读取失败");
        }

        // 使用绝对路径
        String directoryPath = new File("src/main/resources/in").getAbsolutePath();
        String filePath = directoryPath + "/img.png";
        if (!createDirectory(directoryPath)) {
            return Result.fail("目录创建失败");
        }

        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件保存失败");
        }

        try {
            String outputDirectory = new File("src/main/resources/out").getAbsolutePath();
            if (!createDirectory(outputDirectory)) {
                return Result.fail("输出目录创建失败");
            }

            String outputFilePath = FormRecognitionUtil.recognizeForm(filePath, type, outputDirectory);
            System.out.println("生成的文件路径: " + outputFilePath);

            String base64EncodedDocument = encodeFileToBase64(outputFilePath);

            deleteFile(filePath);
            deleteFile(outputFilePath);

            return Result.success(base64EncodedDocument);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("文件内容识别失败");
        }
    }

    private int validateFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            return 0;
        }

        String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
        boolean isFormatSupported = false;
        for (String format : SUPPORTED_FORMATS) {
            if (fileExtension.equals(format)) {
                isFormatSupported = true;
                break;
            }
        }
        if (!isFormatSupported) {
            return 1;
        }

        try {
            byte[] fileBytes = file.getBytes();
            if (fileBytes.length > MAX_FILE_SIZE) {
                return 2;
            }
        } catch (IOException e) {
            return 3;
        }

        return 4;
    }

    private boolean createDirectory(String path) {
        File directory = new File(path);
        if (!directory.exists()) {
            return directory.mkdirs();
        }
        return true;
    }

    private String encodeFileToBase64(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] fileBytes = Files.readAllBytes(file.toPath());
        return Base64.getEncoder().encodeToString(fileBytes);
    }

    private void deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }

    public Result<String> toFont(MultipartFile file) {
        int flagNumber = validateFile(file);
        switch (flagNumber) {
            case 0:
                return Result.fail("文件名不能为空");
            case 1:
                return Result.fail("图片格式不支持");
            case 2:
                return Result.fail("文件大小超过10MB");
            case 3:
                return Result.fail("文件读取失败");
        }

        // 使用绝对路径
        String directoryPath = new File("src/main/resources/in").getAbsolutePath();
        String filePath = directoryPath + "/img.png";
        if (!createDirectory(directoryPath)) {
            return Result.fail("目录创建失败");
        }

        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件保存失败");
        }

        String imagePath = filePath;

        // 调用识别方法
        String result = UniversalCharacterRecognitionUtil.recognizeCharacter(imagePath);

        // 使用 Gson 解析 JSON
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(result, JsonObject.class);

        // 提取所有文本内容
        StringBuilder contentBuilder = new StringBuilder();
        JsonArray pages = jsonObject.getAsJsonArray("pages");
        for (int i = 0; i < pages.size(); i++) {
            JsonObject page = pages.get(i).getAsJsonObject();
            JsonArray lines = page.getAsJsonArray("lines");
            for (int j = 0; j < lines.size(); j++) {
                JsonObject line = lines.get(j).getAsJsonObject();
                JsonArray words = line.getAsJsonArray("words");
                for (int k = 0; k < words.size(); k++) {
                    JsonObject word = words.get(k).getAsJsonObject();
                    contentBuilder.append(word.get("content").getAsString()).append(" ");
                }
            }
        }

        String content = contentBuilder.toString().trim();

        // 打印识别结果
        System.out.println("识别结果: " + result);
        // 输出分析后结果
        System.out.println("提取文本: " + content);

        // 删除图片文件
        File imageFile = new File(imagePath);
        if (imageFile.exists()) {
            if (imageFile.delete()) {
                System.out.println("图片文件已删除: " + imagePath);
            } else {
                System.out.println("无法删除图片文件: " + imagePath);
            }
        } else {
            System.out.println("图片文件不存在: " + imagePath);
        }

        return Result.success(content);
    }

    public Result<String> toLanguage(MultipartFile file, String language) throws Exception {
        int flagNumber = validateFile(file);
        switch (flagNumber) {
            case 0:
                return Result.fail("文件名不能为空");
            case 1:
                return Result.fail("图片格式不支持");
            case 2:
                return Result.fail("文件大小超过10MB");
            case 3:
                return Result.fail("文件读取失败");
        }

        // 使用绝对路径
        String directoryPath = new File("src/main/resources/in").getAbsolutePath();
        String filePath = directoryPath + "/img.png";
        if (!createDirectory(directoryPath)) {
            return Result.fail("目录创建失败");
        }

        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("文件保存失败");
        }

        String content = ImageTextRecognitionUtils.recognizeText(filePath, language);

        // 删除图片文件
        File imageFile = new File(filePath);
        if (imageFile.exists()) {
            if (imageFile.delete()) {
                System.out.println("图片文件已删除: " + filePath);
            } else {
                System.out.println("无法删除图片文件: " + filePath);
            }
        } else {
            System.out.println("图片文件不存在: " + filePath);
        }
        return Result.success(content);
    }
}
